//
//  SSSettingAvatarViewController.m
//  starspaceVR
//
//  Created by 曹端芹 on 17/10/10.
//  Copyright © 2017年 starspace. All rights reserved.
//

#import "SSSettingAvatarViewController.h"
#import "SSUserInfoModel.h"
#import "SSUserInfoManager.h"

#define pictureURL @"http://www.vrspaces.cn"
@interface SSSettingAvatarViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *avatarImgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *avatarHeight;
@property (nonatomic,assign) BOOL isSelectedImage;

@end

@implementation SSSettingAvatarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置头像";
    [self setup];
    
}

- (void) setup {
    
    SSUserInfoModel *userInfo = [[SSUserInfoManager sharedManager] currentUserInfo];
    self.avatarHeight.constant = kRealValue(300);
    [self.avatarImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",pictureURL,userInfo.avatar]] placeholderImage:[UIImage imageNamed:placeholderImageName]];
    
}

- (void)choosePhotoWithSourceType:(UIImagePickerControllerSourceType)sourceType {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];


}
- (IBAction)openPhotoAlbum:(UIButton *)sender {
    [self choosePhotoWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (IBAction)openCamera:(UIButton *)sender {
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear|UIImagePickerControllerCameraDeviceFront]) {
        [self choosePhotoWithSourceType:UIImagePickerControllerSourceTypeCamera];
    }else{
        [self showTip:@"相机不可用"];
        
    }
}
- (IBAction)saveAndupload:(UIButton *)sender {
    
    if (self.isSelectedImage) {
        SSUserInfoModel *userInfo = [[SSUserInfoManager sharedManager] currentUserInfo];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"loginName"] = userInfo.loginName;
        param[@"password"] = userInfo.password;
        param[@"sessionKey"] = userInfo.sessionKey;
        [self showHUD];
        
        NSString *sign = @"1426de94585c43c50c7239905a7da4a8";
        param[@"sign"] = sign;
        NSString *strurl = [NSString stringWithFormat:@"%@sessionKey=%@&loginName=%@&password=%@&sign=%@",kSSUploadAvatarAPI,userInfo.sessionKey,userInfo.loginName,userInfo.password,sign];
        
        NSDictionary *avatarInfo = [self getImageInfo:self.avatarImgView.image];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager.requestSerializer setTimeoutInterval:10];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html",@"application/javascript",@"application/json", nil];
        
        [manager POST:strurl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:avatarInfo[@"imageData"] name:@"Filedata" fileName:avatarInfo[@"fileName"] mimeType:avatarInfo[@"mimeType"]];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self dismissHUD];
            NSString *msg = responseObject[@"msg"];
            if ([msg rangeOfString:@"成功"].location != NSNotFound) {
                [self showTip:@"头像设置成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }else{
                [self showTip:msg];
            
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self dismissHUD];
            NSLog(@"%@",error);
        }];
        
        
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = info[UIImagePickerControllerEditedImage];
        self.avatarImgView.image = image;
        self.isSelectedImage = YES;
        
    }];
}

/**
 * 获取图片名字 ，mimetype和imageData
 */
- (NSDictionary *)getImageInfo:(UIImage *)image {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time = [date timeIntervalSince1970] * 1000000;
    
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *fileName = [NSString stringWithFormat:@"%f.png",time];
    NSString *mimeType = @"image/png";
    if (UIImagePNGRepresentation(image) == nil) {
        imageData = UIImageJPEGRepresentation(image , 1);
        fileName = [NSString stringWithFormat:@"%f.jpg",time];
        mimeType = @"image/jpeg";
    }
    
    return @{@"fileName":fileName,@"mimeType":mimeType,@"imageData":imageData};
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
